﻿//                        ElgProg
//
//    A cheap DIY Arduino based Universal Programmer
//
//    Copyright (C) Elgen };-P aka Morten Overgaard 2015
//
//    This file is part of ElgProg.
//
//    ElgProg is free software: you can redistribute it and/or modify
//    it under the terms of the GNU General Public License as published by
//    the Free Software Foundation, either version 3 of the License, or
//    (at your option) any later version.
//
//    ElgProg is distributed in the hope that it will be useful,
//    but WITHOUT ANY WARRANTY; without even the implied warranty of
//    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
//    GNU General Public License for more details.
//
//    You should have received a copy of the GNU General Public License
//    along with ElgProg. If not, see <http://www.gnu.org/licenses/>.

using System;
using System.Diagnostics;

namespace ElgProg
{
  public static class ArduinoTools
  {
    // More or less "stolen" from here http://forum.arduino.cc/index.php?topic=40309.0
    public static void UploadSketchHex(string sketchHex, string comPort)
    {
      var commandLine =
  @"""C:\Program Files\Arduino\hardware\tools\avr\bin\avrdude"" "
+ @"-C""C:/Program Files/Arduino/hardware/tools/avr/etc/avrdude.conf"" "
+ @"-patmega2560 -cwiring -P{0} -b115200 -D -Uflash:w:""hex/{1}.cpp.hex"":i";

      ProcessStartInfo psI = new ProcessStartInfo("cmd");
      psI.UseShellExecute = false;
      psI.RedirectStandardInput = true;
      psI.RedirectStandardOutput = true;
      psI.RedirectStandardError = true;
      psI.CreateNoWindow = true;
      Process avrprog = new Process();
      avrprog.StartInfo = psI;
      avrprog.Start();
      avrprog.StandardInput.AutoFlush = true;
      avrprog.StandardInput.WriteLine(commandLine, comPort, sketchHex);
      avrprog.StandardInput.Close();
      //Console.WriteLine(avrprog.StandardOutput.ReadToEnd());
      avrprog.StandardOutput.ReadToEnd();
      var errors = avrprog.StandardError.ReadToEnd();
      //if (!String.IsNullOrEmpty(errors))
      //  Console.WriteLine(errors);
      //else
      //avrprog.Close();
      if (avrprog.ExitCode == 0)
        Console.WriteLine("Upload using avrdude succesful! };-P");
      System.Threading.Thread.Sleep(1000);
    }
  }
}